package com.leyou.item.service;

import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.mapper.SpecParamMapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class SpecService {
    private final SpecGroupMapper groupMapper;
    private final SpecParamMapper paramMapper;

    public SpecService(SpecGroupMapper groupMapper, SpecParamMapper paramMapper) {
        this.groupMapper = groupMapper;
        this.paramMapper = paramMapper;
    }

    public List<SpecGroupDTO> queryGroupByCategory(Long categoryId) {
        // 根据record的非空字段查询
        SpecGroup record = new SpecGroup();
        record.setCid(categoryId);
        List<SpecGroup> list = groupMapper.select(record);
        // 转换DTO
        return BeanHelper.copyWithCollection(list, SpecGroupDTO.class);
    }

    public List<SpecParamDTO> querySpecParams(Long gid, Long cid, Boolean searching) {
        // 健壮性判断，gid和cid条件至少传一个
        if(gid == null && cid == null){
            throw new LyException(400, "请求参数必须包含组id或分类id");
        }
        // 根据record的非空字段查询
        SpecParam record = new SpecParam();
        record.setGroupId(gid);
        record.setCid(cid);
        record.setSearching(searching);

        List<SpecParam> list = paramMapper.select(record);
        // 转换DTO
        return BeanHelper.copyWithCollection(list, SpecParamDTO.class);
    }

    public List<SpecGroupDTO> querySpecs(Long categoryId) {
        // 1.根据分类id，查询规格组
        List<SpecGroupDTO> groupList = queryGroupByCategory(categoryId);
        // 2.先查询出分类下的所有参数
        List<SpecParamDTO> params = querySpecParams(null, categoryId, null);
        // 3.把参数按照groupId分组，id一致的放到一个List中，存入Map，key是groupId，值是List
        Map<Long, List<SpecParamDTO>> map = params.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));

        // 4.向规格组中，填入该组下的规格参数
        for (SpecGroupDTO groupDTO : groupList) {
            // 根据组id查询组下的参数
            List<SpecParamDTO> paramList = map.get(groupDTO.getId());
            // 填充参数
            groupDTO.setParams(paramList);
        }
        return groupList;
    }
}
